package solution1.demo1201.demo1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPServer {

    private ServerSocket serverSocket;
    private ExecutorService pool;

    public TCPServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }

    public void start() {
        System.out.println("[TCPServer] 启动!");
        this.pool = Executors.newCachedThreadPool();
        pool.submit(() -> {
            try {
                Socket clientSocket = this.serverSocket.accept();
                handlerSocket(clientSocket);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    private void handlerSocket(Socket clientSocket) throws IOException {
        System.out.println("[TCPServer] 客户端上线！ip: " + clientSocket.getInetAddress() + ", port: " + clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while(true) {
                //1.获取客户端请求
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.返回响应
                writer.println(response);
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("[TCPServer] 客户端下线！ip: " + clientSocket.getInetAddress() + ", port: " + clientSocket.getPort());
            clientSocket.close();
        }
    }

    private String process(String request) {
        System.out.println("[TCPServer] 收到客户端请求: " + request);
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPServer server = new TCPServer(9090);
        server.start();
    }

}
